---
title: MariaDB
---

```{=mdx}
<Tip>
**Compatibility**

Only available on Node.js.
</Tip>
```

This requires MariaDB 11.7 or later version

This guide provides a quick overview for getting started with mariadb [vector stores](/oss/concepts/#vectorstores). For detailed documentation of all `MariaDB store` features and configurations head to the [API reference](https://api.js.langchain.com/classes/langchain_community_vectorstores_mariadb.MariaDBStore.html).

## Overview

### Integration details

| Class | Package | [PY support](https://python.langchain.com/docs/integrations/vectorstores/mariadb/) | Version |
| :--- | :--- | :---: | :---: |
| [`MariaDBStore`](https://api.js.langchain.com/classes/langchain_community_vectorstores_mariadb.MariaDBStore.html) | [`@langchain/community`](https://npmjs.com/@langchain/community) | ✅ | ![NPM - Version](https://img.shields.io/npm/v/@langchain/community?style=flat-square&label=%20&) |

## Setup

To use MariaDBVector vector stores, you'll need to set up a MariaDB 11.7 version or later with the [`mariadb`](https://www.npmjs.com/package/mariadb) connector as a peer dependency.

This guide will also use [OpenAI embeddings](/oss/integrations/text_embedding/openai), which require you to install the `@langchain/openai` integration package. You can also use [other supported embeddings models](/oss/integrations/text_embedding) if you wish.

We'll also use the [`uuid`](https://www.npmjs.com/package/uuid) package to generate ids in the required format.

```{=mdx}
import IntegrationInstallTooltip from "@mdx_components/integration_install_tooltip.mdx";
<IntegrationInstallTooltip></IntegrationInstallTooltip>

<Npm2Yarn>
  @langchain/community @langchain/openai @langchain/core mariadb uuid
</Npm2Yarn>
```

### Setting up an instance

Create a file with the below content named docker-compose.yml:

```yaml
# Run this command to start the database:
# docker-compose up --build
version: "3"
services:
  db:
    hostname: 127.0.0.1
    image: mariadb/mariadb:11.7-rc
    ports:
      - 3306:3306
    restart: always
    environment:
      - MARIADB_DATABASE=api
      - MARIADB_USER=myuser
      - MARIADB_PASSWORD=ChangeMe
      - MARIADB_ROOT_PASSWORD=ChangeMe
    volumes:
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql
```

And then in the same directory, run docker compose up to start the container.

### Credentials

To connect to you MariaDB instance, you'll need corresponding credentials. For a full list of supported options, see the [`mariadb` docs](https://github.com/mariadb-corporation/mariadb-connector-nodejs/blob/master/documentation/promise-api.md#connection-options).

If you are using OpenAI embeddings for this guide, you'll need to set your OpenAI key as well:

```typescript
process.env.OPENAI_API_KEY = "YOUR_API_KEY";
```

If you want to get automated tracing of your model calls you can also set your [LangSmith](https://docs.smith.langchain.com/) API key by uncommenting below:

```typescript
// process.env.LANGCHAIN_TRACING_V2="true"
// process.env.LANGCHAIN_API_KEY="your-api-key"
```

## Instantiation

To instantiate the vector store, call the `.initialize()` static method. This will automatically check for the presence of a table, given by `tableName` in the passed `config`. If it is not there, it will create it with the required columns.

```typescript
import { OpenAIEmbeddings } from "@langchain/openai";

import {
   DistanceStrategy,
   MariaDBStore,
} from "@langchain/community/vectorstores/mariadb";
import { PoolConfig } from "mariadb";

const config = {
  connectionOptions: {
    type: "mariadb",
    host: "127.0.0.1",
    port: 3306,
    user: "myuser",
    password: "ChangeMe",
    database: "api",
  } as PoolConfig,
  distanceStrategy: 'EUCLIDEAN' as DistanceStrategy,
};
const vectorStore = await MariaDBStore.initialize(
  new OpenAIEmbeddings(),
   config
);
```

## Manage vector store

### Add items to vector store

```typescript
import { v4 as uuidv4 } from "uuid";
import type { Document } from "@langchain/core/documents";

const document1: Document = {
  pageContent: "The powerhouse of the cell is the mitochondria",
  metadata: { source: "https://example.com" }
};

const document2: Document = {
  pageContent: "Buildings are made out of brick",
  metadata: { source: "https://example.com" }
};

const document3: Document = {
  pageContent: "Mitochondria are made out of lipids",
  metadata: { source: "https://example.com" }
};

const document4: Document = {
  pageContent: "The 2024 Olympics are in Paris",
  metadata: { source: "https://example.com" }
}

const documents = [document1, document2, document3, document4];

const ids = [uuidv4(), uuidv4(), uuidv4(), uuidv4()]

// ids are not mandatory, but that's for the example
await vectorStore.addDocuments(documents, { ids: ids });
```

### Delete items from vector store

```typescript
const id4 = ids[ids.length - 1];

await vectorStore.delete({ ids: [id4] });
```

## Query vector store

Once your vector store has been created and the relevant documents have been added you will most likely wish to query it during the running of your chain or agent.

### Query directly

Performing a simple similarity search can be done as follows:

```typescript
const similaritySearchResults = await vectorStore.similaritySearch("biology", 2, { "year": 2021 });
for (const doc of similaritySearchResults) {
  console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);
}
```

```output
* The powerhouse of the cell is the mitochondria [{"year": 2021}]
* Mitochondria are made out of lipids [{"year": 2022}]
```

The above filter syntax use be more complex:

```json
# name = 'martin' OR firstname = 'john'
let res = await vectorStore.similaritySearch("biology", 2, {"$or": [{"name":"martin"}, {"firstname", "john"}] });
```

If you want to execute a similarity search and receive the corresponding scores you can run:

```typescript
const similaritySearchWithScoreResults = await vectorStore.similaritySearchWithScore("biology", 2)

for (const [doc, score] of similaritySearchWithScoreResults) {
  console.log(`* [SIM=${score.toFixed(3)}] ${doc.pageContent} [${JSON.stringify(doc.metadata)}]`);
}
```

```output
* [SIM=0.835] The powerhouse of the cell is the mitochondria [{"source":"https://example.com"}]
* [SIM=0.852] Mitochondria are made out of lipids [{"source":"https://example.com"}]
```

### Query by turning into retriever

You can also transform the vector store into a [retriever](/oss/langchain/retrieval) for easier usage in your chains.

```typescript
const retriever = vectorStore.asRetriever({
  // Optional filter
  // filter: filter,
  k: 2,
});
await retriever.invoke("biology");
```

```output
[
  Document {
    pageContent: 'The powerhouse of the cell is the mitochondria',
    metadata: { source: 'https://example.com' },
    id: undefined
  },
  Document {
    pageContent: 'Mitochondria are made out of lipids',
    metadata: { source: 'https://example.com' },
    id: undefined
  }
]
```

### Usage for retrieval-augmented generation

For guides on how to use this vector store for retrieval-augmented generation (RAG), see the following sections:

- [Build a RAG app with LangChain](/oss/langchain/rag).
- [Agentic RAG](/oss/langgraph/agentic-rag)
- [Retrieval docs](/oss/langchain/retrieval)

## Advanced: reusing connections

You can reuse connections by creating a pool, then creating new `MariaDBStore` instances directly via the constructor.

Note that you should call `.initialize()` to set up your database at least once to set up your tables properly before using the constructor.

```typescript
import { OpenAIEmbeddings } from "@langchain/openai";
import { MariaDBStore } from "@langchain/community/vectorstores/mariadb";
import mariadb from "mariadb";

// First, follow set-up instructions at
// https://js.langchain.com/docs/modules/indexes/vector_stores/integrations/mariadb

const reusablePool = mariadb.createPool({
  host: "127.0.0.1",
  port: 3306,
  user: "myuser",
  password: "ChangeMe",
  database: "api",
});

const originalConfig = {
  pool: reusablePool,
  tableName: "testlangchainjs",
  collectionName: "sample",
  collectionTableName: "collections",
  columns: {
    idColumnName: "id",
    vectorColumnName: "vect",
    contentColumnName: "content",
    metadataColumnName: "metadata",
  },
};

// Set up the DB.
// Can skip this step if you've already initialized the DB.
// await MariaDBStore.initialize(new OpenAIEmbeddings(), originalConfig);
const mariadbStore = new MariaDBStore(new OpenAIEmbeddings(), originalConfig);

await mariadbStore.addDocuments([
  { pageContent: "what's this", metadata: { a: 2 } },
  { pageContent: "Cat drinks milk", metadata: { a: 1 } },
]);

const results = await mariadbStore.similaritySearch("water", 1);

console.log(results);

/*
  [ Document { pageContent: 'Cat drinks milk', metadata: { a: 1 } } ]
*/

const mariadbStore2 = new MariaDBStore(new OpenAIEmbeddings(), {
  pool: reusablePool,
  tableName: "testlangchainjs",
  collectionTableName: "collections",
  collectionName: "some_other_collection",
  columns: {
    idColumnName: "id",
    vectorColumnName: "vector",
    contentColumnName: "content",
    metadataColumnName: "metadata",
  },
});

const results2 = await mariadbStore2.similaritySearch("water", 1);

console.log(results2);

/*
  []
*/

await reusablePool.end();
```

## Closing connections

Make sure you close the connection when you are finished to avoid excessive resource consumption:

```typescript
await vectorStore.end();
```

## API reference

For detailed documentation of all `MariaDBStore` features and configurations head to the [API reference](https://api.js.langchain.com/classes/langchain_community_vectorstores_mariadb.MariaDBStore.html).
